﻿using PortalWeb.CMS.Dao;
using PortalWeb.Core.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PortalWeb.CMS.Business;
using PortalWeb.Models.Cms;
using PortalWeb.CMS.Core.Entity;

namespace PortalWeb.Areas.CmsAdmin.Controllers
{
    [Authorize]
    public class ProductController : Controller
    {
        public ProductController()
            : this(new ProductManager(),
                new CommonModelManager(),
                new AttachmentManager())
        {
        }

        public ProductController(ProductManager productManager, CommonModelManager commonModelManager,
            AttachmentManager attachmentManager)
        {
            ProductManager = productManager;
            CommonModelManager = commonModelManager;
            AttachmentManager = attachmentManager;
        }

        public ProductManager ProductManager { get; private set; }
        public CommonModelManager CommonModelManager { get; private set; }
        public AttachmentManager AttachmentManager { get; private set; }
        
        public ActionResult Menu()
        {
            return PartialView();
        }
        public ActionResult List()
        {
            return View();
        }

        //
        // GET: /Products/
        [Authorize]
        public ActionResult JsonList(string title, string input, int? category, DateTime? fromDate, DateTime? toDate,
            int pageIndex = 1, int pageSize = 20)
        {
            if (category == null)
                category = 0;
            int offset = pageSize*(pageIndex - 1);
            int limint = pageSize*pageIndex;
            var rows = CommonModelManager.LoadPageEntities(p => p.Model == "Product", false, p => p.ReleaseDate, offset,
                limint).Select(cm => new CommonModelViewModel()
                {
                    Id = cm.Id,
                    Inputer = cm.Inputer,
                    Hits = cm.Hits,
                    ReleaseDate = cm.ReleaseDate,
                    CategoryId = cm.Category.Id,
                    CategoryName = cm.Category.Name,
                    DefaultPicUrl = cm.DefaultPicUrl,
                    Title = cm.Title,
                    Status = cm.Status,
                });
            return Json(new {total = CommonModelManager.Count(), rows = rows});
        }

        // GET: /Admin/News/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Product product = ProductManager.Get(id);
            ProductViewModel model = new ProductViewModel(product);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(model);
        }


        // GET: /Admin/News/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Product product = ProductManager.Get(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(new ProductViewModel(product));
        }

        // POST: /Admin/News/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit()
        {
            int id = int.Parse(ControllerContext.RouteData.GetRequiredString("id"));
            var product = ProductManager.Get(id);
            TryUpdateModel(product, new string[] { "Author", "Source", "Intro", "Content" });
            TryUpdateModel(product.CommonModel, new string[] { "CategoryId", "Title", "DefaultPicUrl" });
            // "CommonModel", 
            if (ModelState.IsValid)
            {
                if (ProductManager.Update(product))
                {
                    //附件处理
                    var attachments =
                        AttachmentManager.FindList(product.CommonModel.Id, User.Identity.Name, string.Empty, true)
                            .ToList();
                    foreach (var att in attachments)
                    {
                        var filePath = Url.Content(att.FileParth);
                        if ((product.CommonModel.DefaultPicUrl != null &&
                             product.CommonModel.DefaultPicUrl.IndexOf(filePath) >= 0) ||
                            product.Content.IndexOf(filePath) > 0)
                        {
                            att.ModelId = product.Id;
                            AttachmentManager.Update(att);
                        }
                        else
                        {
                            System.IO.File.Delete(Server.MapPath(att.FileParth));
                            AttachmentManager.Delete(att);
                        }
                    }
                    return View("EditSucess", new ProductViewModel(product));
                }
            }
            return View(new ProductViewModel(product));
        }

       /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">文章id</param>
        /// <returns></returns>
        public JsonResult Delete(int id)
        {
            //删除附件
            var product = ProductManager.Get(id);
            if (product == null) return Json(false);
            //附件列表
            var attachmentList = product.CommonModel.Attachment;
            var commonModel = CommonModelManager.Get(id);
            //删除文章
            if (ProductManager.Delete(product))
            {
                //删除附件文件
                foreach (var attachment in attachmentList)
                {
                    System.IO.File.Delete(Server.MapPath(attachment.FileParth));
                }
                //删除公共模型
                CommonModelManager.Delete(commonModel);
                return Json(true);
            }
            else return Json(false);
        }


        // GET: /Admin/News/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Admin/News/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [ValidateInput(false)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Product product)
        {
            product.CommonModel = new CommonModel();
            TryUpdateModel(product.CommonModel, new string[] { "CategoryId", "Title", "DefaultPicUrl" });
            if (ModelState.IsValid)
            {
                //设置固定值
                product.CommonModel.Hits = 0;
                product.CommonModel.Inputer = User.Identity.Name;
                product.CommonModel.Model = "Product";
                product.CommonModel.ReleaseDate = System.DateTime.Now;
                product.CommonModel.Status = 99;
                product = ProductManager.Add(product);
                if (product.Id > 0)
                {
                    //查询相关附件
                    var attachments = AttachmentManager.FindList(null, User.Identity.Name, string.Empty).ToList();
                    //遍历附件
                    foreach (var att in attachments)
                    {
                        var filePath = Url.Content(att.FileParth);
                        //文章首页图片或内容中使用了该附件则更改ModelID为文章保存后的ModelID
                        if ((product.CommonModel.DefaultPicUrl != null &&
                             product.CommonModel.DefaultPicUrl.IndexOf(filePath) >= 0) ||
                            product.Content.IndexOf(filePath) > 0)
                        {
                            att.ModelId = product.Id;
                            AttachmentManager.Update(att);
                        }
                        //未使用改附件则删除附件和数据库中的记录
                        else
                        {
                            System.IO.File.Delete(Server.MapPath(att.FileParth));
                            AttachmentManager.Delete(att);
                        }
                    }
                    return View("AddSucess", new ProductViewModel(product));
                }
            }
            return View(new ProductViewModel(product));
        }
    }
}